package ebiz.buddhist.texts;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;


import com.nbpcorp.mobilead.sdk.MobileAdListener;
import com.nbpcorp.mobilead.sdk.MobileAdView;

import ebiz.buddhist.texts.data.BowCounterHelper;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.SystemClock;
import android.os.PowerManager.WakeLock;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

import android.widget.TextView;
import android.widget.Toast;

public class CountMain extends Activity implements MobileAdListener {
	BowCounterHelper mHelper; // 2012/1/21 sekisuri add DB
	MediaPlayer mPlayer;
	TelephonyManager mTelMan; //------- 통화시 mp3 play 중지 
	private MobileAdView adView = null;

//	EditText mStartEdit, mEndEdit, mPeriodEdit;
	//CheckBox mSound;
	TextView mNowPageText, mRemainText;
	Button mBtnStart, mBtnPause ;
	int mNowPage, mRemain;
	SoundPool mPool;
	int mSheet;
    PowerManager mPm;
    WakeLock mWakeLock;

    final static int IDLE = 0;
    final static int COUNTING = 1;
    final static int PAUSE = 2;
    int mStatus = IDLE;
    int start;
    int end;
    int period;
    int mSoundSelect;
    boolean sound;
    
    TextView mEllapse;
	TextView mSplit;
	long mBaseTime;
	long mPauseTime;
	long mEndTime;
	
	String revFileName,mpFileName,mpPath;
	boolean mResumeAfterCall; //------- 통화시 mp3 play 중지 

	final static int RUNNING = 1;
	
    
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.countmain);
		// adView 만들기
	      adView = (MobileAdView) findViewById(R.id.adview1);
	      adView.setListener(this);
		  adView.start();
		  
		mPlayer = new MediaPlayer();
		mHelper = new BowCounterHelper(this);
		mNowPageText = (TextView)findViewById(R.id.nowpage);
		mRemainText = (TextView)findViewById(R.id.remain);
// sekisuri adding total timer		
		mEllapse = (TextView)findViewById(R.id.ellapse);
//end
		
		// 프레프런스에서 정보 읽음
		SharedPreferences pref = getSharedPreferences("CountSet",0);
		revFileName = pref.getString("mSpinSelect", "파일지정");
		start = pref.getInt("start",0);
		end = pref.getInt("end", 108);
		period = pref.getInt("period", 12);
		sound = pref.getBoolean("sound", false);
		mSoundSelect = pref.getInt("mSoundSelect", mSoundSelect);

		mpFileName = mpReNameEn(revFileName);

		File SDCardRoot = Environment.getExternalStorageDirectory(); 
		mpPath = SDCardRoot + "/buddhist/" + mpFileName;
		if(mSoundSelect == 2)
		{
			LoadMedia(mpPath);
		}
		
		// 책장 넘기는 소리
		mPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
		mSheet = mPool.load(this, R.raw.default_sound01, 1);

		// 버튼의 핸들러 연결
        mBtnStart = (Button)findViewById(R.id.btnstart); 
        mBtnStart.setOnClickListener(mClickListener);
        mBtnPause = (Button)findViewById(R.id.btnpause); 
        mBtnPause.setOnClickListener(mClickListener);
        

        //------- 통화시 mp3 play 중지 
        mTelMan = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
  	    mTelMan.listen(mCallListener, PhoneStateListener.LISTEN_CALL_STATE);
  	  //------- 통화시 mp3 play 중지 
		mPlayer.setOnCompletionListener(mOnComplete);

        // WakeLock 객체 생성
        mPm = (PowerManager)getSystemService(Context.POWER_SERVICE);
        mWakeLock = mPm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "tag");
        
        setCountTitle();
	}

	// 떠 있는 동안 화면 유지. 백그라운드 카운팅도 실용성 있어 카운팅 중에만 유지하는 정책은 좋지 않음
    protected void onResume() {
        super.onResume();
        mWakeLock.acquire();
    }
    
    protected void onPause() {
        super.onPause();
        if (mWakeLock.isHeld()) {
            mWakeLock.release();
        }
    }
    
    Button.OnClickListener mClickListener = new View.OnClickListener() {
		public void onClick(View v) {

			switch (v.getId()) {
			case R.id.btnstart:

				if (mStatus != IDLE) {
					mTimerHandler.removeMessages(0);
					
					if(mSoundSelect == 2)
					{
						mPlayer.start();
					}					
				}			
				// 시작 페이지, 남은 시간만 읽고 타이머 바로 동작.
				// 끝, 시간, 사운드 여부는 중간에 바뀔 수도 있으므로 지금 조사하지 않음
				int endpage;  // sekisuri 이거 왜 선언했는지 모르것네.. 밑에 조건문에서 쓰다가 
							 // sekisuri 지운 것 같은데 혹시나 해서 걍 나둠
				try {
					
					mNowPage = start; //Integer.parseInt(mStartEdit.getText().toString());
					endpage = end; //Integer.parseInt(mEndEdit.getText().toString());
					mRemain =  period - 1; //Integer.parseInt(mPeriodEdit.getText().toString()) - 1;
				}
				catch (NumberFormatException e) {
					Toast.makeText(CountMain.this, 
							" " + getString(R.string.message_timerange), 
							Toast.LENGTH_LONG).show();
					return;
				}
				
			//	if (mNowPage >= endpage) {
		//			Toast.makeText(CountMain.this, 
		//					getString(R.string.message_countrange), 
		//					Toast.LENGTH_LONG).show();
		//			return;
		//		}
				
				if(mSoundSelect == 2)
				{
					if(!mPlayer.isPlaying())
					{
						mPlayer.start();
					}
				}				
				mNowPageText.setText(Integer.toString(mNowPage));
				mRemainText.setText(Integer.toString(mRemain));

				
				
				mStatus = COUNTING;
				mBtnPause.setText(getString(R.string.btn_pause));
//				sekisuri adding total timer
				mTimer.sendEmptyMessage(0);
				mBaseTime = SystemClock.elapsedRealtime();
//					end
				mBtnPause.setEnabled(true);
				mBtnStart.setEnabled(false);// sekisuri 시작시 시작버튼 비활성
	//			mStartEdit.setEnabled(false);// sekisuri setting text false;
	//			mEndEdit.setEnabled(false);// sekisuri setting text false;
	//			mPeriodEdit.setEnabled(false);// sekisuri setting text false;
			
				mTimerHandler.sendEmptyMessageDelayed(0,1000);
				break;
			case R.id.btnpause:
				if (mStatus == IDLE) {
					return;
				}
				if (mStatus == PAUSE) {
					mStatus = COUNTING;
					mBtnPause.setText(getString(R.string.btn_pause));
					mTimerHandler.sendEmptyMessageDelayed(0,1000);
//	sekisuri 2012/1/20 adding total timer 계속버튼
					long now = SystemClock.elapsedRealtime();
					mBaseTime += (now - mPauseTime);
					mTimer.sendEmptyMessage(0);
					if(mSoundSelect == 2)
					{
						if(mPlayer.isPlaying() == false)
						{
							mPlayer.start();
						}						
					}			
//	end
				} else {
					mStatus = PAUSE;
					mBtnPause.setText(getString(R.string.btn_continue));
//	sekisuri 2012/1/20 adding total timer 중지 버튼 눌렸을때 
					mTimer.removeMessages(0);
					mPauseTime = SystemClock.elapsedRealtime();
					
					
					if(mSoundSelect == 2)
					{
						if(mPlayer.isPlaying())
						{
							mPlayer.pause();
						}						
					}			
//		end	
				}
				break;
		
			}
		}
	};

	Handler mTimerHandler = new Handler() {
		public void handleMessage(Message msg) {
			if (mStatus == PAUSE) {
				return;
			}
			
			if (mRemain != 0) {
				mRemain--;
				mRemainText.setText(Integer.toString(mRemain));
				mTimerHandler.sendEmptyMessageDelayed(0,1000);
			} else {
				// 소리부터 낸다.
				//if (mSound.isChecked()) {
				if(sound){
					mPool.play(mSheet, 1, 1, 0, 0, 1);
				}

				// 끝 페이지를 지워 버렸으면 즉시 독서를 종료한다.
				int endpage;
				try {
					endpage = end ; //Integer.parseInt(mEndEdit.getText().toString());
				}
				catch (NumberFormatException e) {
					endpage = -1;
				}
				
				if (mNowPage < endpage) {
					mNowPage++;
					mNowPageText.setText(Integer.toString(mNowPage));

					// 시간을 지워 버렸으면 12초로 디폴트 처리한다.
					try {
						mRemain = period; //Integer.parseInt(mPeriodEdit.getText().toString()) - 1;
					}
					catch (NumberFormatException e) {
						mRemain = 12;
					}

					mRemainText.setText(Integer.toString(mRemain));
					mTimerHandler.sendEmptyMessageDelayed(0,1000);
				} else {
//sekisuri 2012/01/21 adding bow timer 종료시 총시간을 멈춘다
					mTimer.removeMessages(0);
					mPauseTime = SystemClock.elapsedRealtime();
//end
					if(mSoundSelect == 2)
					{
						if(mPlayer.isPlaying())
						{
							mPlayer.reset();
						}
					}		
					Toast.makeText(CountMain.this, 
							" " + getString(R.string.message_finish), Toast.LENGTH_LONG).show();
					mStatus = IDLE;
					mEndTime = SystemClock.elapsedRealtime();
					alertSaveData();
				}
			}
		}
	};
// 2012/1/20 sekisuri adding bow timer 
	Handler mTimer = new Handler() {
		public void handleMessage(Message msg) {
			mEllapse.setText(getEllapse());
			mTimer.sendEmptyMessage(0);
		}
	};
	String getEllapse() {
		long now = SystemClock.elapsedRealtime();
		long ell = now - mBaseTime;
		String sEll = String.format("%02d분%02d초", ell / 1000 / 60, 
				(ell / 1000) % 60);
		return sEll;
	}
	long getRunTime()
	{
		long ell = mEndTime - mBaseTime;
		return ell;
	}
//end
	
	

// 2012/1/21 sekisuri 현재시간
	public String currentTime()
	{
		SimpleDateFormat mDateTime = new SimpleDateFormat("yyyy년MM월dd일 HH시mm분",Locale.KOREA);
		Date mCurrentTime = new Date();
		String mTime = mDateTime.format(mCurrentTime);
		return mTime;
	}
//end
	public void SaveDb()
	{
		String currTime = currentTime();
	//	String currTime = "2012년03월02일 19시52분";  //sekisuri 테스트용

		Calendar cal = Calendar.getInstance();
	//	int start = Integer.parseInt(mStartEdit.getText().toString());
	//	int end = Integer.parseInt(mEndEdit.getText().toString());
		int bows = end - start;
		String realTime =  String.format("%d",getRunTime());
		String countAndTime = getString(R.string.string_playcount) + " " + bows +"  " +
				getString(R.string.string_playtime)  + " " + getEllapse();
		//	String countAndTime = "수행 횟수: " + 108 +"  수행시간 : " + "30분00초"; //sekisuri 테스트용

		int currMonth = cal.get(Calendar.MONTH)+1; // 현재 월
		
		SQLiteDatabase db;
		db = mHelper.getWritableDatabase();
		db.execSQL("insert into bowcount values(null,"+ bows + "," + currMonth + ",'"+ realTime + "','" + 
				currTime+ "','" + countAndTime + "');");
/*		
		db.execSQL("insert into bowcount values(null,"+ 108 + "," + 3 + ",'"+ 1800000 + "','" + 
							currTime+ "','" + countAndTime + "');");
*/		 //sekisuri 테스트용
		mHelper.close();
		
	}
	
	void alertSaveData()
	{
		new AlertDialog.Builder(CountMain.this)
		.setTitle(getString(R.string.dialog_alert))
		.setMessage(getString(R.string.dialog_save))
		.setPositiveButton(getString(R.string.dialog_yes), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {			
				SaveDb();	
				startActivity(new Intent(CountMain.this,CountRead.class));//sekisuri 저장후 bowread activity로 이동
			}
		})				
		.setNegativeButton(getString(R.string.dialog_no), null)
		.show();
	}
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		
		menu.add(0,1,0,getString(R.string.menu_setting));
		menu.add(0,2,0,getString(R.string.menu_viewdata));
		menu.add(0,3,0,getString(R.string.menu_restart));
		return true;
	}
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 1:
		finish();
		startActivity(new Intent(CountMain.this, CountSetting.class));		
		return true;
		case 2:
		startActivity(new Intent(CountMain.this, CountRead.class));
		return true;			
		case 3:
		mTimerHandler.removeMessages(0);
		finish();
		startActivity(new Intent(CountMain.this,CountMain.class));
		return true;	
		}		
		return false;
	}
// sekisuri 종료시 사운드를 초기화하고 mStatus를 idle상태로 만든다
	/*
	 public boolean onKeyDown(int keyCode, KeyEvent event) {
		  if(event.getAction() == KeyEvent.ACTION_DOWN){
		   if(keyCode == KeyEvent.KEYCODE_BACK){
				mTimerHandler.removeMessages(0);
			    finish();
			   }
			
			   return true;
		   }
		  return false;
		 }*/
	 
	
//end
	 public String mpReNameEn(String str)
	 {
		 String strCompare = str;
		   if(strCompare.compareTo(getString(R.string.item_chunsu))== 0)
			   strCompare = "chunsu.mp3";
		   if(strCompare.compareTo(getString(R.string.item_sutra))== 0)
			   strCompare = "heartsutra.mp3";
		   if(strCompare.compareTo(getString(R.string.item_beopseong))== 0)
			   strCompare = "beopseong.mp3";
		   if(strCompare.compareTo(getString(R.string.item_hwaeom))== 0)
			   strCompare = "hwaeom.mp3";
		   if(strCompare.compareTo(getString(R.string.item_sinju)) == 0)
			   strCompare = "sinju.mp3";

 //---------------  음질이 안좋아서 삭제
		   if(strCompare.compareTo(getString(R.string.item_kanmu)) == 0)
			   strCompare = "kanmu.mp3";
		   if(strCompare.compareTo(getString(R.string.item_bodalbomun)) == 0)
			   strCompare = "bodalbomun.mp3";
		   if(strCompare.compareTo(getString(R.string.item_kanja)) == 0)
			   strCompare = "kanja.mp3";	
//-----------------------------------
		   
		   if(strCompare.compareTo(getString(R.string.item_gwaneum)) == 0)
			   strCompare = "gwaneum.mp3";
		   if(strCompare.compareTo(getString(R.string.item_ami)) == 0)
			   strCompare = "ami.mp3";
		   
		   if(strCompare.compareTo(getString(R.string.item_kukrak)) == 0)
			   strCompare = "kukrak.mp3";
		   if(strCompare.compareTo(getString(R.string.item_musang)) == 0)
			   strCompare = "musang.mp3";
		   if(strCompare.compareTo(getString(R.string.item_kang1)) == 0)
			   strCompare = "kang1.mp3";
		   if(strCompare.compareTo(getString(R.string.item_kang2)) == 0)
			   strCompare = "kang2.mp3";
		   if(strCompare.compareTo(getString(R.string.item_kang3)) == 0)
			   strCompare = "kang3.mp3";
		   if(strCompare.compareTo(getString(R.string.item_kang4)) == 0)
			   strCompare = "kang4.mp3";	   
		   if(strCompare.compareTo(getString(R.string.item_kor_heartsutra)) == 0)
			   strCompare = "han_heartsutra.mp3";
		   if(strCompare.compareTo(getString(R.string.item_kor_chunsu)) == 0)
			   strCompare = "han_chunsu.mp3";
		   if(strCompare.compareTo(getString(R.string.item_chunji)) == 0)
			   strCompare = "chunji.mp3";
		   if(strCompare.compareTo(getString(R.string.item_sinmyo)) == 0)
			   strCompare = "sinmyo.mp3";
		   if(strCompare.compareTo(getString(R.string.item_yebull))==0)
			   strCompare = "yebull.mp3";
		   if(strCompare.compareTo(getString(R.string.item_prajna))==0)
			   strCompare = "prajna.mp3";
		   
		   if(strCompare.compareTo(getString(R.string.item_bows07)) == 0)
			   strCompare = "108_7.mp3";
		   if(strCompare.compareTo(getString(R.string.item_bows08)) == 0)
			   strCompare = "108_8.mp3";
		   if(strCompare.compareTo(getString(R.string.item_bows09)) == 0)
			   strCompare = "108_9.mp3";
		   if(strCompare.compareTo(getString(R.string.item_bows10)) == 0)
			   strCompare = "108_10.mp3";
		   if(strCompare.compareTo(getString(R.string.item_bows11)) == 0)
			   strCompare = "108_11.mp3";
		   if(strCompare.compareTo(getString(R.string.item_bows_s)) == 0)
			   strCompare = "108bow.mp3";
		   if(strCompare.compareTo(getString(R.string.item_bows_youngin)) == 0)
			   strCompare = "108bow_youngin.mp3";
		   

		   if(strCompare.compareTo(getString(R.string.item_medicine_buddha)) == 0)
			   strCompare = "MedicineBuddha.mp3";
		   if(strCompare.compareTo(getString(R.string.cundi)) == 0)
			   strCompare = "MantraOfBodhisattvaCundi.mp3";
		   if(strCompare.compareTo(getString(R.string.monks)) == 0)
			   strCompare = "Monks_of_Tibet_Healing.mp3";
		   if(strCompare.compareTo(getString(R.string.zen_master)) == 0)
			   strCompare = "Korean_Zen_master.mp3";
		   
		   if(strCompare.compareTo(getString(R.string.item_chant)) == 0)
			   strCompare = "chant.mp3";
		   if(strCompare.compareTo(getString(R.string.item_followyourheart)) == 0)
			   strCompare = "followyourheart.mp3";
		   if(strCompare.compareTo(getString(R.string.item_windy_hermitage)) == 0)
			   strCompare = "windy_hermitage.mp3";
		   if(strCompare.compareTo(getString(R.string.item_healing_music)) == 0)
			   strCompare = "healing_music.mp3";
		   
		   if(strCompare.compareTo(getString(R.string.Buddhist_hymn_3)) == 0)
			   strCompare = "Buddhist_hymn3.mp3";
		   
	
		   if(strCompare.compareTo(getString(R.string.item_diamond)) == 0)
			   strCompare = "diamond_sutra.mp3";
		   
		   if(strCompare.compareTo(getString(R.string.item_sakyamuni)) == 0)
			   strCompare = "sakyamuni.mp3";
		   
		   if(strCompare.compareTo(getString(R.string.item_guan)) == 0)
			   strCompare = "guan.mp3";
		  
		   
		   if(strCompare.compareTo(getString(R.string.mp3_meditation)) == 0)
			   strCompare = "jeongmok_1.mp3";
		   
		   if(strCompare.compareTo(getString(R.string.mp3_meditation_2)) == 0)
			   strCompare = "jeongmok_2.mp3";
			   
		   return strCompare;
	 }
	 boolean LoadMedia(String idx) {
			try {
				mPlayer.setDataSource(idx);
			} catch (IllegalArgumentException e) {
				return false;
			} catch (IllegalStateException e) {
				return false;
			} catch (IOException e) {
				return false;
			}
			if (Prepare() == false) {
				return false;
			}
			return true;
	   }
	 boolean Prepare() {
			try {
				mPlayer.prepare();
			} catch (IllegalStateException e) {
				return false;
			} catch (IOException e) {
				return false;
			}
			return true;
	   }
	  //------- 통화시 mp3 play 중지 
		PhoneStateListener mCallListener = new PhoneStateListener() {
			public void onCallStateChanged (int state, String incomingNumber) {
				switch (state) {
				case TelephonyManager.CALL_STATE_IDLE:
					if (mResumeAfterCall) {
					/*	
						mTextCall.postDelayed(new Runnable() {
							public void run() {
								mPlayer.start();
							}
						}, 3000);
					*/	
						mPlayer.start();
					}
					break;
				case TelephonyManager.CALL_STATE_RINGING:
					// 전화오면 즉시 재생 중지
					if (mPlayer.isPlaying()) {
						mPlayer.pause();
						mResumeAfterCall = true;
					} else {
						mResumeAfterCall = false;
					}
					break;
				case TelephonyManager.CALL_STATE_OFFHOOK:
					break;
				}
			}
		};
		  //------- 통화시 mp3 play 중지
		
		void setCountTitle()
		{
			switch(mSoundSelect)
			{
			case 0:
				setTitle("소리 설정 : 없음");
				break;
			case 1:
				setTitle("소리 설정 : 간격시 종소리");
				break;
			case 2:
				setTitle("소리 설정 : 배경음악 : " + revFileName);
				break;
				
			}
		}
		MediaPlayer.OnCompletionListener mOnComplete = 
			  	new MediaPlayer.OnCompletionListener() {
					public void onCompletion(MediaPlayer arg0) {
						mPlayer.reset();
						LoadMedia(mpPath);
						mPlayer.start();
					}
			  };


				@Override
				protected void onDestroy() {
					super.onDestroy();
					
					if (adView != null) {
						adView.destroy();
						adView = null;
					}
					if (mPlayer != null) {
				       	mPlayer.release();
				       	mPlayer = null;
				       }
					mTelMan.listen(mCallListener, PhoneStateListener.LISTEN_NONE);
					mTimerHandler.removeMessages(0);
					
				}

				public void onReceive(int err) {
					// event for receive ad 
					
				}
}
